package com.fifth.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.Cart;
import com.fifth.common.pojo.entity.Goods;
import com.fifth.common.pojo.entity.Order;
import com.fifth.common.pojo.entity.Stock;
import com.fifth.order.config.HttpClient;
import com.fifth.order.feign.GoodsFeign;
import com.fifth.order.mapper.CartMapper;
import com.fifth.order.mapper.OrderMapper;
import com.fifth.order.mapper.StockMapper;
import com.fifth.order.service.OrderService;
import com.fifth.order.vo.*;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @作者：刘壬杉
 * @创建时间 2022/9/1 9:47
 **/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private GoodsFeign goodsFeign;

    @Autowired
    private Redisson redisson;

    //微信支付需要的配置
    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    //支付宝支付需要的配置
    @Value("${alipay.app_id}")
    private String aliAppId;
    @Value("${alipay.private_key}")
    private String aliPrivateId;
    @Value("${alipay.public_key}")
    private String aliPublicKey;
    @Value("${alipay.getway_url}")
    private String aliGetwayUrl;

    /**
     * 点击购买按钮立即购买
     * 并根据订单编号生成支付二维码
     *
     * @param order
     * @return
     */
    @Transactional
    @Override
    public CommonResult buyNow(Order order) {
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        String telephone;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
            telephone = user.getString("telephone");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        //校验商品状态
        Integer goodsStatus =  goodsFeign.checkGoodsStatus(order.getGoodsid());
        if (goodsStatus==1){
            return new CommonResult(5001,"商品已下架,暂时无法购买",null);
        }
        //添加订单编号
        String orderNo = UUID.randomUUID().toString().replace("-", "");
        if (order.getCode().equals("")){
            //配置订单信息
            //添加用户id
            order.setUid(userid);
            order.setCode(orderNo);
            //添加订单生成时间
            order.setOrderdate(LocalDateTime.now());
            //订单状态
            order.setState(1);
            //发货状态
            order.setSend(0);
            //评论状态
            order.setCommentstatus(0);
            //总价
            order.setTotalmoney(order.getPrice().multiply(new BigDecimal(order.getNum())));
            //将订单添加到order表中
            int insert = orderMapper.insert(order);
            if (insert != 1) {
                return new CommonResult(5000, "下单失败,请稍后再试", null);
            }
        }else {
            //根据code修改paysort
            Order order1 = new Order();
            order1.setPaysort(order.getPaysort());
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code",order.getCode());
            orderMapper.update(order1,queryWrapper);
        }
        //根据订单编号生成支付二维码
        //判断支付类型 0微信 1支付宝
        Integer paysort = order.getPaysort();
        String goodsid = order.getGoodsid();
        //根据goodsid查库存
        QueryWrapper<Stock> queryWrapperStock = new QueryWrapper<>();
        queryWrapperStock.eq("goods_id",goodsid);
        Stock stock = stockMapper.selectOne(queryWrapperStock);
        if (stock.getResidue()-order.getNum()<0){
            //让订单失效
            Order order1 =new Order();
            order1.setState(3);
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code",order.getCode());
            orderMapper.update(order1,queryWrapper);
            return new CommonResult(7000,"库存不足,支付失败",null);
        }
        //生成微信二维码
        if (paysort == 0) {
            try {
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //允许http请求
                httpClient.setHttps(true);
                //根据orderno查询信息(待支付state=1 )
                QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                if (order.getCode().equals("")){
                    queryWrapper.eq("code", orderNo);
                }else {
                    queryWrapper.eq("code",order.getCode());
                }
                queryWrapper.eq("state", 1);
                Order orderInfo = orderMapper.selectOne(queryWrapper);
                if (orderInfo != null) {
                    Map<String, String> map = new HashMap<>();
                    //公众账号ID
                    map.put("appid", appId);
                    //商户号
                    map.put("mch_id", mchId);
                    //设备号
                    map.put("device_info", telephone);
                    //随机字符串
                    map.put("nonce_str", WXPayUtil.generateNonceStr());
                    //商品描述
                    map.put("body", "买商品");
                    //商户订单号
                    if (!order.getCode().equals("")){
                        map.put("out_trade_no", order.getCode());
                    }else {
                        map.put("out_trade_no", orderNo);
                    }
                    //标价金额
                    map.put("total_fee", new BigDecimal(1).longValue() + "");
                    //通知地址
                    map.put("notify_url", "https://192.168.1.23:8081/system/pay/back");
                    //交易类型
                    map.put("trade_type", "NATIVE");
                    //发送的参数
                    httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
                    httpClient.post();
                    String content = httpClient.getContent();
                    Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);
                    if (xmlToMap.get("result_code").equals("SUCCESS")) {
                        Map<String, Object> result = new HashMap<>();
                        result.put("codeUrl", xmlToMap.get("code_url"));
                        result.put("price", order.getTotalmoney());
                        if (!order.getCode().equals("")){
                            result.put("orderNo", order.getCode());
                        }else {
                            result.put("orderNo", orderNo);
                        }
                        return new CommonResult(2000, "请求支付二维码成功", result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(7000, "后端问题", null);
            }
            return new CommonResult(6000, "订单已失效,请重新下单", null);
        } else {
            //生成支付宝二维码
            try {
                QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                if (order.getCode().equals("")){
                    queryWrapper.eq("code", orderNo);
                }else {
                    queryWrapper.eq("code",order.getCode());
                }
                queryWrapper.eq("state", 1);
                Order orderInfo = orderMapper.selectOne(queryWrapper);
                if (orderInfo != null) {
                    AlipayClient alipayClient = new DefaultAlipayClient(aliGetwayUrl, aliAppId, aliPrivateId, "json", "utf-8", aliPublicKey, "RSA2");
                    AlipayTradePrecreateRequest Alirequest = new AlipayTradePrecreateRequest();
                    if (!order.getCode().equals("")){
                        // 支付请求
                        Alirequest.setBizContent("{" +
                                "    \"out_trade_no\":\"" + order.getCode() + "\"," +//商户订单号
                                "    \"total_amount\":\"" + order.getTotalmoney() + "\"," +
                                "    \"subject\":\"" + goodsFeign.goodsByIdName(order.getGoodsid()) + "当面付" + "\"," +
                                "    \"store_id\":\"" + order.getBid() + "\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                                "    \"timeout_express\":\"5m\"}");//订单允许的最晚付款时间
                    }else {
                        // 支付请求
                        Alirequest.setBizContent("{" +
                                "    \"out_trade_no\":\"" + orderNo + "\"," +//商户订单号
                                "    \"total_amount\":\"" + order.getTotalmoney() + "\"," +
                                "    \"subject\":\"" + goodsFeign.goodsByIdName(order.getGoodsid()) + "当面付" + "\"," +
                                "    \"store_id\":\"" + order.getBid() + "\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                                "    \"timeout_express\":\"5m\"}");//订单允许的最晚付款时间
                    }
                    AlipayTradePrecreateResponse response = alipayClient.execute(Alirequest);
                    if (!response.isSuccess()) {
                        System.out.println("生成支付宝订单失败:" + response.getMsg());
                    }
                    String qrCode = response.getQrCode();
                    Map<String, Object> map = new HashMap<>();
                    map.put("codeUrl", qrCode);
                    map.put("price", order.getTotalmoney());
                    if (!order.getCode().equals("")){
                        map.put("orderNo", order.getCode());
                    }else {
                        map.put("orderNo",orderNo);
                    }
                    return new CommonResult(2000, "成功", map);
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return new CommonResult(8000, "下单失败,请稍后再试", null);
        }
    }

    /**
     * 在购物车页面点击去结算,修改购物车中被选中商品的状态,并添加到订单中,返回统一的订单编号
     *
     * @param getOrderVos
     * @return 订单编号
     */
    @Transactional
    @Override
    public CommonResult settlement(List<GetOrderVo> getOrderVos) {
        //获取userid
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        //根据goodsids修改cart表中对应商品的状态为1
        for (GetOrderVo getOrderVo : getOrderVos) {
            getOrderVo.setUid(userid);
            getOrderVo.setTotalmoney(getOrderVo.getPrice().multiply(new BigDecimal(getOrderVo.getNum())));
        }
        Integer updatenums = cartMapper.updateState(getOrderVos);
        if (updatenums == 0) {
            return new CommonResult(4000, "生成订单失败", null);
        }
        //生成统一订单信息
        String code = UUID.randomUUID().toString().replace("-", "");
        //批量添加到order表
        for (GetOrderVo getOrderVo : getOrderVos) {
            getOrderVo.setCode(code);
        }
        Integer integer = orderMapper.insertByGoodsids(getOrderVos);
        if (integer == 0) {
            return new CommonResult(4000, "生成订单失败", null);
        }
        return new CommonResult(2000, "生成订单成功", code);
    }

    /**
     * 根据订单号查询订单信息
     *
     * @return
     */
    @Override
    public CommonResult selectByCode(String code) {
        List<Map> orderInfo = orderMapper.selectByCode(code);
        if (orderInfo.size() == 0) {
            return new CommonResult(4000, "暂无订单信息", null);
        }
        Set<String> set = new HashSet<>();
        for (Map map : orderInfo) {
            String bid = (String) map.get("bid");
            set.add(bid);
        }
        List<List<Map>> result = new ArrayList<>();
        for (String s : set) {
            List<Map> list = new ArrayList<>();
            for (Map map : orderInfo) {
                if (s.equals(map.get("bid"))){
                    list.add(map);
                }
            }
            result.add(list);
        }
        System.out.println(result);
        return new CommonResult(2000, "查询订单信息成功",result);
    }

    /**
     * 支付当前订单生成二维码
     *
     * @param paysort
     * @param code
     * @return
     */
    @Transactional
    @Override
    public CommonResult paySort(Integer paysort, String code) {
        //获取锁对象
        RLock lock = redisson.getLock("pay::" + code);
        //根据code查找商品id
        QueryWrapper<Order> getGoodsid = new QueryWrapper<>();
        getGoodsid.eq("code", code);
        List<Order> orders = orderMapper.selectList(getGoodsid);
        List<String> goodsids = orders.stream().map(Order::getGoodsid).collect(Collectors.toList());
        //校验商品状态
        for(String goodsid : goodsids) {
            Integer goodsStatus =  goodsFeign.checkGoodsStatus(goodsid);
            if (goodsStatus==1){
                return new CommonResult(5001,"购买商品中包含已下架商品,暂时无法购买",null);
            }
        }
        //根据goodsid查库存
        List<Stock> stocks = stockMapper.selectByGoodsids(goodsids);
        for (Stock stock : stocks) {
            Integer residue = stock.getResidue();
            String goodsId = stock.getGoodsId();
            for (Order order : orders) {
                Integer num = order.getNum();
                String goodsid = order.getGoodsid();
                //如果下单量大于库存剩余量
                if (residue - num < 0 && goodsid.equals(goodsId)) {
                    //当前订单失效(修改订单状态为3)
                    Order order1 = new Order();
                    order1.setState(3);
                    QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", code);
                    orderMapper.update(order1, queryWrapper);
                    return new CommonResult(7000, "抱歉,当前订单中包含库存不足商品,订单已失效", null);
                }
            }
        }
        try {//Redission上锁
            lock.lock(30, TimeUnit.SECONDS);
            //根据code修改订单支付方式
            Order order = new Order();
            order.setPaysort(paysort);
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            int update = orderMapper.update(order, queryWrapper);
            if (update == 0) {
                return new CommonResult(4000, "生成二维码失败", null);
            }
            //获取到requset
            HttpServletRequest request = WebUtils.getRequest();
            //获取token
            String token = request.getHeader("token");
            //根据token获取userid和手机号
            String telephone = "";
            String s = redisTemplate.opsForValue().get(token);
            if (s != null && s.length() != 0) {
                Map userMap = JSON.parseObject(s, Map.class);
                if (userMap != null && userMap.containsKey("user")) {
                    JSONObject user = (JSONObject) userMap.get("user");
                    telephone = user.getString("telephone");
                } else {
                    return new CommonResult(4000, "暂未登录,请登录后再购买", null);
                }
            }
            //获取订单信息
            List<Map> maps = orderMapper.selectByCode(code);
            //处理总价
            BigDecimal totalmoney = new BigDecimal("0");
            //处理商品描述
            StringBuffer desc = new StringBuffer();
            for (Map map : maps) {
                BigDecimal money = (BigDecimal) map.get("totalmoney");
                totalmoney = totalmoney.add(money);
                String gname = (String) map.get("gname");
                desc.append(gname + " ");
            }
            //0微信支付 1支付宝支付
            if (paysort == 0) {
                try {
                    HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                    //允许http请求
                    httpClient.setHttps(true);
                    if (maps.size() != 0) {
                        Map<String, String> map = new HashMap<>();
                        //公众账号ID
                        map.put("appid", appId);
                        //商户号
                        map.put("mch_id", mchId);
                        //设备号
                        map.put("device_info", telephone);
                        //随机字符串
                        map.put("nonce_str", WXPayUtil.generateNonceStr());
                        //商品描述
                        map.put("body","买商品");
                        //商户订单号
                        map.put("out_trade_no", code);
                        //标价金额
                        map.put("total_fee", new BigDecimal(1).longValue() + "");
                        //通知地址
                        map.put("notify_url", "https://192.168.1.23:8081/system/pay/back");
                        //交易类型
                        map.put("trade_type", "NATIVE");
                        //发送的参数
                        httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
                        httpClient.post();
                        String content = httpClient.getContent();
                        Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);
                        if (xmlToMap.get("result_code").equals("SUCCESS")) {
                            Map<String, Object> result = new HashMap<>();
                            result.put("codeUrl", xmlToMap.get("code_url"));
                            result.put("price", totalmoney);
                            return new CommonResult(2000, "请求支付二维码成功", result);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return new CommonResult(7000, "后端问题", null);
                }
                return new CommonResult(6000, "订单已失效,请重新下单", null);
            } else {
                try {
                    if (maps.size() != 0) {
                        AlipayClient alipayClient = new DefaultAlipayClient(aliGetwayUrl, aliAppId, aliPrivateId, "json", "utf-8", aliPublicKey, "RSA2");
                        AlipayTradePrecreateRequest Alirequest = new AlipayTradePrecreateRequest();
                        // 支付请求
                        Alirequest.setBizContent("{" +
                                "    \"out_trade_no\":\"" + code + "\"," +//商户订单号
                                "    \"total_amount\":\"" + totalmoney + "\"," +
                                "    \"subject\":\"" + desc + "当面付" + "\"," +
                                "    \"store_id\":\"10001\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                                "    \"timeout_express\":\"5m\"}");//订单允许的最晚付款时间
                        AlipayTradePrecreateResponse response = alipayClient.execute(Alirequest);
                        if (!response.isSuccess()) {
                            System.out.println("生成支付宝订单失败:" + response.getMsg());
                        }
                        String qrCode = response.getQrCode();
                        Map<String, Object> map = new HashMap<>();
                        map.put("codeUrl", qrCode);
                        map.put("price", totalmoney);
                        return new CommonResult(2000, "成功", map);
                    }
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                return new CommonResult(8000, "下单失败,请稍后再试", null);
            }
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    /**
     * 根据orderid,userid,支付状态查询订单信息
     *
     * @param
     * @return
     */
    @Override
    public Order addComment(String code, String goodsid) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0);
        queryWrapper.eq("code", code);
        queryWrapper.eq("goodsid", goodsid);
        return orderMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件分页查询订单信息
     *
     * @param pageCurrent
     * @param pageSize
     * @param zhuangtai
     * @return
     */
    @Override
    public CommonResult findOrder(Integer pageCurrent, Integer pageSize, String zhuangtai) {
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        IPage<Order> page = new Page<>(pageCurrent, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",userid);
        if (zhuangtai != null && !zhuangtai.equals("") && !zhuangtai.equals("5")) {
            queryWrapper.eq("o_order.state", zhuangtai);
        }
        //查询未评价订单
        else if (zhuangtai.equals("5")) {
            //已付款
            queryWrapper.eq("o_order.state", 0);
            //未评价
            queryWrapper.eq("commentstatus", 0);
        }
        //查询全部
        else {
            queryWrapper.eq("uid",userid);
            /*queryWrapper.eq("o_order.state", "1");
            queryWrapper.or();
            queryWrapper.eq("o_order.state", "0");
            queryWrapper.or();
            queryWrapper.eq("o_order.state", "3");
            queryWrapper.or();
            queryWrapper.eq("o_order.state", "4");*/
        }
        IPage<Order> ipage = orderMapper.findOrder(page, queryWrapper);
        List<Order> orderList = ipage.getRecords();
        List<String> codes = new ArrayList<>();
        for (Order order : orderList) {
            codes.add(order.getCode());
        }
        if (codes.size() == 0) {
            return new CommonResult(2000, "查询成功", ipage);
        }
        List<Order> goodsByCode = orderMapper.selectGoodsByCode(codes);
        for (Order order : orderList) {
            String code = order.getCode();
            LocalDateTime orderdate = order.getOrderdate();
            String format = orderdate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            order.setTime(format);
            List<Goods> list = new ArrayList<>();
            BigDecimal totalmoney = new BigDecimal("0");
            for (Order o : goodsByCode) {
                if (code.equals(o.getCode())) {
                    list.add(o.getGoods());
                    order.setGoodsList(list);
                    order.setGoods(null);
                    totalmoney = totalmoney.add(o.getTotalmoney());
                }
            }
            order.setTotalmoney(totalmoney);
        }
        return new CommonResult(2000, "查询成功", ipage);
    }

    /**
     * 根据订单id取消订单
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult delOrder(String id) {
        Order order = new Order();
        order.setState(4);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        orderMapper.update(order, queryWrapper);
        return new CommonResult(2000, "删除成功", null);
    }

    /**
     * 根据code删除订单
     *
     * @param code
     * @return
     */
    @Override
    public CommonResult deleteOrder(String code) {
        Order order = new Order();
        order.setState(2);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        orderMapper.update(order, queryWrapper);
        return new CommonResult(2000, "删除成功", null);
    }

    /**
     * 修改订单状态为失效
     *
     * @param code
     * @return
     */
    @Override
    public CommonResult updateStateToFailure(String code) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        Order order = new Order();
        order.setState(3);
        orderMapper.update(order, queryWrapper);
        return new CommonResult(2000, "修改成功", null);
    }

    /**
     * 根据goodsid获取商品成交量
     *
     * @param goodsid
     * @return
     */
    @Override
    public Integer getGoodsSellNum(String goodsid) {
        Integer num = orderMapper.getGoodsSellNum(goodsid);
        return num;
    }

    /**
     * 结算购物车付款
     * @param payCartVo
     * @return
     */
    @Override
    public CommonResult buyCart(PayCartVo payCartVo) {
        //根据传入的addrid修改订单的addrid
        Order order = new Order();
        order.setAddrid(payCartVo.getAddrid());
        order.setPaysort(payCartVo.getPaysort());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",payCartVo.getCode());
        orderMapper.update(order,queryWrapper);
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        String telephone = "";
        String s = redisTemplate.opsForValue().get(token);
        if (s != null && s.length() != 0) {
            Map userMap = JSON.parseObject(s, Map.class);
            if (userMap != null && userMap.containsKey("user")) {
                JSONObject user = (JSONObject) userMap.get("user");
                telephone = user.getString("telephone");
            } else {
                return new CommonResult(4000, "暂未登录,请登录后再购买", null);
            }
        }
        //根据code查找商品id
        QueryWrapper<Order> getGoodsid = new QueryWrapper<>();
        getGoodsid.eq("code", payCartVo.getCode());
        List<Order> orders = orderMapper.selectList(getGoodsid);
        List<String> goodsids = orders.stream().map(Order::getGoodsid).collect(Collectors.toList());
        //校验商品状态
        for(String goodsid : goodsids) {
            Integer goodsStatus =  goodsFeign.checkGoodsStatus(goodsid);
            if (goodsStatus==1){
                return new CommonResult(5001,"购买商品中包含已下架商品,暂时无法购买",null);
            }
        }
        //根据goodsid查库存
        List<Stock> stocks = stockMapper.selectByGoodsids(goodsids);
        for (Stock stock : stocks) {
            Integer residue = stock.getResidue();
            String goodsId = stock.getGoodsId();
            for (Order o : orders) {
                Integer num = o.getNum();
                String goodsid = o.getGoodsid();
                //如果下单量大于库存剩余量
                if (residue - num < 0 && goodsid.equals(goodsId)) {
                    //当前订单失效(修改订单状态为3)
                    Order order1 = new Order();
                    order1.setState(3);
                    QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("code",  payCartVo.getCode());
                    orderMapper.update(order1, queryWrapper1);
                    return new CommonResult(7000, "抱歉,当前订单中包含库存不足商品,订单已失效", null);
                }
            }
        }
        if (payCartVo.getPaysort()==0){
            //微信支付
            try {
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //允许http请求
                httpClient.setHttps(true);
                Map<String, String> map = new HashMap<>();
                //公众账号ID
                map.put("appid", appId);
                //商户号
                map.put("mch_id", mchId);
                //设备号
                map.put("device_info", telephone);
                //随机字符串
                map.put("nonce_str", WXPayUtil.generateNonceStr());
                //商品描述
                map.put("body", "买商品");
                //商户订单号
                map.put("out_trade_no", payCartVo.getCode());
                //标价金额
                map.put("total_fee", new BigDecimal(1).longValue() + "");
                //通知地址
                map.put("notify_url", "https://192.168.1.23:8081/system/pay/back");
                //交易类型
                map.put("trade_type", "NATIVE");
                //发送的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
                httpClient.post();
                String content = httpClient.getContent();
                Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);
                if (xmlToMap.get("result_code").equals("SUCCESS")) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("codeUrl", xmlToMap.get("code_url"));
                    return new CommonResult(2000, "请求支付二维码成功", result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(7000, "后端问题", null);
            }
            return new CommonResult(6000, "订单已失效,请重新下单", null);
        } else {
            try {
                    AlipayClient alipayClient = new DefaultAlipayClient(aliGetwayUrl, aliAppId, aliPrivateId, "json", "utf-8", aliPublicKey, "RSA2");
                    AlipayTradePrecreateRequest Alirequest = new AlipayTradePrecreateRequest();
                    // 支付请求
                    Alirequest.setBizContent("{" +
                            "    \"out_trade_no\":\"" + payCartVo.getCode() + "\"," +//商户订单号
                            "    \"total_amount\":\"" + payCartVo.getTotalmoney() + "\"," +
                            "    \"subject\":\"当前购物测商品结算" + "\"," +
                            "    \"store_id\":\"10001\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                            "    \"timeout_express\":\"5m\"}");//订单允许的最晚付款时间
                    AlipayTradePrecreateResponse response = alipayClient.execute(Alirequest);
                    if (!response.isSuccess()) {
                        System.out.println("生成支付宝订单失败:" + response.getMsg());
                    }
                    String qrCode = response.getQrCode();
                    Map<String, Object> map = new HashMap<>();
                    map.put("codeUrl", qrCode);
                    return new CommonResult(2000, "成功", map);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return new CommonResult(8000, "下单失败,请稍后再试", null);
        }
    }

    /**
     * 库存不足生成支付二维码失败将购物车商品返还
     * @param getOrderVos
     * @return
     */
    @Override
    public CommonResult changeCart(List<GetOrderVo> getOrderVos) {
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        List<String> ids = new ArrayList<>();
        for (GetOrderVo getOrderVo : getOrderVos) {
            String id = getOrderVo.getId();
            ids.add(id);
        }
        //修改购物车的逻辑删除为0
        cartMapper.changeCart(ids,userid);
        return new CommonResult(2000,"修改成功",null);
    }

    /**
     * 商家的订单管理的页面加载
     * @param currentPage
     * @param pageSize
     * @param businessOrderVo
     * @return
     */
    @Override
    public CommonResult selectAllOrders(Integer currentPage, Integer pageSize, BusinessOrderVo businessOrderVo) {
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        String telephone;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
            telephone = user.getString("telephone");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        String gname = businessOrderVo.getGname();
        IPage<Order> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("o_order.uid",userid);
        if (businessOrderVo.getSend()!=null){
            queryWrapper.eq("send",businessOrderVo.getSend());
        }
        if (  businessOrderVo.getGname()!= null){
            queryWrapper.like("g_goods.gname",businessOrderVo.getGname());
        }
        if (businessOrderVo.getGname()==null && businessOrderVo.getSend()==null){
            queryWrapper = null;
        }
        IPage<Order> pageCodes = orderMapper.getCodes(page,queryWrapper);
        List<Order> orders = pageCodes.getRecords();
        //获取分页的订单号集合
        List<String> allCode = new ArrayList<>();
        for (Order order : orders) {
            allCode.add(order.getCode());
        }
        //获取订单号查询详细信息
        if (allCode.size()!=0) {
            List<Order> orderInfo = orderMapper.selectAllOrders(allCode,userid);
            List<Order> tableList = new ArrayList<>();
            for (String code : allCode) {
                List<Order> orderlist = new ArrayList<>();
                Order order = new Order();
                order.setCode(code);
                Integer sum = 0;
                BigDecimal totalmoney = new BigDecimal(0);
                for (Order record : orderInfo) {
                    if (record.getCode().equals(code)) {
                        orderlist.add(record);
                        sum += record.getNum();
                        totalmoney = totalmoney.add(record.getTotalmoney());
                        order.setAddr(record.getAddr());
                        order.setOrderdate(record.getOrderdate());
                        order.setSend(record.getSend());
                    }
                }
                order.setOrder(orderlist);
                order.setTotalmoney(totalmoney);
                order.setNum(sum);
                tableList.add(order);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("total",pageCodes.getTotal());
            map.put("tableList",tableList);
            return new CommonResult(2000,"查询成功",map);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",0);
        map.put("records",null);
        map.put("tableList",null);
        return new CommonResult(2000,"查询成功",map);

    }

    /**
     * 根据订单编号修改发货状态
     * @param code
     * @return
     */
    @Override
    public CommonResult updateSend(String code) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        Order order = new Order();
        order.setSend(1);
        orderMapper.update(order,queryWrapper);
        return new CommonResult(2000,"修改发货状态成功",null);
    }

    /**
     * 判断该用户是否买过该商品
     * @param id
     * @return
     */
    @Override
    public CommonResult hasBuyThisGoods(String id) {
        //获取到requset
        HttpServletRequest request = WebUtils.getRequest();
        //获取token
        String token = request.getHeader("token");
        //根据token获取userid和手机号
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "暂未登录,请登录后再购买", null);
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",userid);
        queryWrapper.eq("goodsid",id);
        queryWrapper.eq("state",0);
        List<Order> list = orderMapper.selectList(queryWrapper);
        if (list.size()==0){
            return new CommonResult(5000,"未购买过该商品,无法评论",null);
        }
        return new CommonResult(2000,"购买过该商品",null);
    }

    /**
     * 修改订单评论状态
     * @param goodsid
     * @param uid
     * @return
     */
    @Override
    public Integer updateOrderCommentStatus(String goodsid, String uid) {
        Order order = new Order();
        order.setCommentstatus(1);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goodsid",goodsid);
        queryWrapper.eq("uid",uid);
        queryWrapper.eq("state",0);
        return orderMapper.update(order,queryWrapper);
    }
}
